package com.github.service.gen;



import com.github.bean.config.ImageCaptchaConfig;
import com.github.util.ShapeUtil;
import com.github.util.RandomUtil;

import java.awt.*;

/**
 * 生成图形验证码抽象类
 */
public abstract class ImageCaptchaGenerator {

    /**
     * 图形验证码配置
     */
    protected ImageCaptchaConfig captchaConfig;

    /**
     * 字母内容
     */
    protected String letter;


    protected ImageCaptchaGenerator(ImageCaptchaConfig captchaConfig, String letter) {
        this.captchaConfig = captchaConfig;
        this.letter = letter;
    }


    /**
     * 生成图片 base64
     * @return  图片 base64
     */
    public abstract String gen();



    /**
     * 画背景
     *
     * @param graphics graphics 对象
     */
    protected void fillBackGround(Graphics2D graphics) {
        String[] rgba = captchaConfig.getCodeColor().split("[,;]");
        graphics.setPaint(new Color(Integer.parseInt(rgba[0]), Integer.parseInt(rgba[1]), Integer.parseInt(rgba[2]), Integer.parseInt(rgba[3])));
        graphics.fill(new Rectangle(0, 0, captchaConfig.getImageWidth(), captchaConfig.getImageHeight()));
    }


    /**
     * 绘制字符
     *
     * @param graphics graphics 对象
     * @param captcha  验证码字符串
     */
    protected abstract void drawLetter(Graphics2D graphics, String captcha);

    /**
     * 在绘制干扰图形
     *
     * @param graphics graphics 对象
     */
    protected void interfereLetter(Graphics2D graphics) {
        AlphaComposite ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1F * RandomUtil.genNum(6, 10));
        graphics.setComposite(ac3);
        BasicStroke stroke = new BasicStroke(2.5F);
        ShapeUtil.drawQuadCurve2D(graphics, captchaConfig.getImageWidth(), captchaConfig.getImageHeight(), RandomUtil.genColor(), stroke);
        ShapeUtil.drawOval(graphics, captchaConfig.getImageWidth(), captchaConfig.getImageHeight(), RandomUtil.genColor(), stroke);
    }


}
